import axios from 'axios'
import store from '../store'
import router from '../router'
import { apilist } from './config.js'
import { getStore, clearStore } from 'utils/util'
import qs from 'qs'

import { message } from 'ant-design-vue/es'

var myLoading
var myMessage = null

//请求拦截
axios.interceptors.request.use(
  (config) => {
    if (config.loading) {
      store.state.loading = true
    }

    return config
  },
  (error) => {
    store.state.loading = false
    return Promise.reject(error)
  }
)

//响应拦截
axios.interceptors.response.use(
  (response) => {
    store.state.loading = false
    return response
  },
  (error) => {
    store.state.loading = false
    let { response, config } = error
    if (error.message.indexOf('timeout') != -1) {
      return Promise.reject({
        code: 'timeout',
        message: config.timeoutMsg || '请求超时,请确认您网络连接状态'
      })
    }

    if (response) {
      switch (response.status) {
        case 400:
          store.state.loading = false
          break
        case 401:
          store.state.loading = false
          break
        case 500:
          store.state.loading = false
      }

      return Promise.reject(response.data)
    } else {
      message.error('服务器响应错误,请稍后刷新重试~')
      return Promise.reject('服务器响应错误,请稍后刷新重试~')
    }
  }
)

//http封装
function Axios({ url, method, params, header = {}, ...other }) {
  url = apilist[url]
  let { timeout } = other

  let token = getStore('token') || undefined
  if (token) {
    header.token = token
  }

  header = Object.assign(
    {
      'Content-Type': 'application/json;chatset=utf-8'
    },
    header
  )

  let setting = {
    method: method,
    url: url,
    headers: header,
    timeout: timeout || 10000,
    loading: true,
    ...other
  }

  method == 'GET' ? (setting.params = params) : (setting.data = params)

  if (header['Content-Type'] == 'application/x-www-form-urlencoded') {
    setting.transformRequest = [
      function (params) {
        params = qs.stringify(params)
        return params
      }
    ]
  } else if (header['Content-Type'] == 'multipart/form-data') {
    let formData = new FormData()
    for (let item in setting.data) {
      formData.append(item, setting.data[item])
    }
    setting.data = formData
  }
  return new Promise((resolve, reject) => {
    axios(setting)
      .then((res) => {
        if (res.data.code === '20001') {
          myLoading && myLoading.close()

          clearStore()
          store.commit('setToken', '')
          store.commit('setInfo', {})
          store.commit('setRoles', [])

          if (myMessage) {
            message.destroy()
          }

          let option = {
            type: 'error',
            content: res.data.msg
          }

          myMessage = message.open(option)

          router.push('/login')
        } else {
          resolve(res.data)
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function _get(setting) {
  setting.method = 'GET'

  return Axios(setting)
}

export function _post(setting) {
  setting.method = 'POST'
  return Axios(setting)
}

export function _all(setting) {
  let pro = setting.map((item) => {
    return _post(item)
  })

  return Promise.all(pro)
}
